package com.ll.blog.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ll.blog.common.ApiResponse;
import com.ll.blog.contant.Constant;
import com.ll.blog.contant.ExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


public class UserFilter implements Filter {
    @Autowired
    StringRedisTemplate redisTemplate;

    private  static final ThreadLocal<Integer> USER = new ThreadLocal<>();

    public static Integer getUser(){
        return USER.get();
    }

    private  static final ThreadLocal<Integer> Role = new ThreadLocal<>();

    public static Integer getRole(){
        return Role.get();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        servletResponse.setCharacterEncoding("UTF-8");
        String token = httpServletRequest.getHeader("Authorization");
        // 没有携带token
        if (token ==null || token.isEmpty()){
            PrintWriter writer = servletResponse.getWriter();
            writer.write(ApiResponse.error(ExceptionEnum.TOKEN_ERROR).toString());
            writer.flush();
            writer.close();
            return;
        }
        Algorithm algorithm = Algorithm.HMAC256(Constant.JWT_KEY);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        try {
            DecodedJWT jwt = jwtVerifier.verify(token);
            Integer role = jwt.getClaim(Constant.role).asInt();
            Integer UserId = jwt.getClaim(Constant.user_id).asInt();
            Role.set(role);
            USER.set(UserId);

        } catch (TokenExpiredException e){
            PrintWriter writer = servletResponse.getWriter();
            writer.write(ApiResponse.error(ExceptionEnum.TOKEN_ERROR).toString());
            writer.flush();
            writer.close();
            return;
        } catch (JWTDecodeException e){
            PrintWriter writer = servletResponse.getWriter();
            writer.write(ApiResponse.error(ExceptionEnum.TOKEN_ERROR).toString());
            writer.flush();
            writer.close();
            return;
        }
        // token过期
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String s = operations.get(token);
        if(s==null || !s.equals(token)){
            PrintWriter writer = servletResponse.getWriter();
            writer.write(ApiResponse.error(ExceptionEnum.TOKEN_ERROR).toString());
            writer.flush();
            writer.close();
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
